package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.FeedBack;
import com.web.exiaodao.business.repository.FeedBackRepository;
import com.web.exiaodao.business.service.FeedBackService;

@Service("FeedBackService")
@Transactional(readOnly = false)
public class FeedBackServiceImpl extends BaseService<FeedBack> implements FeedBackService {

	@Autowired
	private FeedBackRepository feedBackRepository;
	
	/**
	 * 查询单条FeedBack信息
	 * @param tId
	 * @return 返回单个FeedBack对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<FeedBack> findOne(Long modelId) throws BusinessException {
		FeedBack obj = new FeedBack();
		if(modelId != 0){
			obj = feedBackRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<FeedBack> xr = new XaResult<FeedBack>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
		} else {
			throw new BusinessException(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的FeedBack数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象FeedBack集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<FeedBack>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<FeedBack> page = feedBackRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FeedBack.class), pageable);
		XaResult<Page<FeedBack>> xr = new XaResult<Page<FeedBack>>();
		xr.setObject(page);
		return xr;
	}

	/**
	 * 分页查询状态status的FeedBack数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象FeedBack集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<FeedBack>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<FeedBack> page = feedBackRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FeedBack.class), pageable);
		XaResult<Page<FeedBack>> xr = new XaResult<Page<FeedBack>>();
		xr.setObject(page);
		return xr;
	}

	/**
	 * 保存FeedBack信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<FeedBack> saveOrUpdate(FeedBack model) throws BusinessException {
		FeedBack obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = feedBackRepository.findOne(model.getId());
		}else{
			obj = new FeedBack();
		}
		obj.setUserId(model.getUserId());
		obj.setContent(model.getContent());
		obj.setUrl(model.getUrl());
		obj = feedBackRepository.save(obj);
		XaResult<FeedBack> xr = new XaResult<FeedBack>();
		xr.setObject(obj);
		return xr;
	}

	/**
	 * 修改FeedBack状态，可一次修改多条   3删除  -1锁定  1正常
	 * @param userId
	 * @param modelIds
	 * @param status
	 * @return 返回FeedBack对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<FeedBack> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<FeedBack> xr = new XaResult<FeedBack>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				FeedBack obj = feedBackRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = feedBackRepository.save(obj);
				} else {
					throw new BusinessException(XaConstant.Message.object_not_find);
				}
			}
		}
		return xr;
	}
	
	/**
	 * 意见反馈分页查询并查询用户名
	 */
	@Override
	public XaResult<Page<FeedBack>> findFeedBackList(Integer nextPage, Integer pageSize,
			Map<String, Object> filterParams) throws BusinessException {
		//select f.id,f.content,f.url,u.user_name,f.create_time from tb_xa_feedback f left join tb_xa_user u on u.id = f.user_id WHERE f.STATUS<> 3 ORDER BY f.create_time
		StringBuffer sql=new StringBuffer("select f.id,f.content,f.url,u.user_name,f.create_time ");
		sql.append("from tb_xa_feedback f left join tb_xa_user u on u.id = f.user_id ");
		sql.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
		//统计数据库中数据个数
		StringBuffer sql1=new StringBuffer("select count(*) ");
		sql1.append("from tb_xa_feedback f left join tb_xa_user u on u.id = f.user_id ");
		sql1.append(" WHERE f.STATUS<> ").append(XaConstant.Status.delete);
		//查询条件
				
				if(XaUtil.isNotEmpty(filterParams.get("EQ_user_name"))){
					sql.append(" AND u.user_name= '").append(filterParams.get("EQ_user_name")).append("' ");
					sql1.append(" AND u.user_name= '").append(filterParams.get("EQ_user_name")).append("' ");
				}
				
				if(XaUtil.isNotEmpty(filterParams.get("LIKE_content"))){
					sql.append(" AND f.content ").append(" like '%").append(filterParams.get("LIKE_content")).append("%' ");
					sql1.append(" AND f.content ").append(" like '%").append(filterParams.get("LIKE_content")).append("%' ");
				}
				if(XaUtil.isNotEmpty(filterParams.get("LTE_createTime"))){
					sql.append(" AND f.create_time <= '").append(filterParams.get("LTE_createTime")).append("' ");;
					sql1.append(" AND f.create_time <= '").append(filterParams.get("LTE_createTime")).append("' ");;
				}
				if(XaUtil.isNotEmpty(filterParams.get("BETWEEN_createTime"))){
					String s = (String) filterParams.get("BETWEEN_createTime");
					String[] str = s.split(",");
					sql.append(" AND f.create_time between '").append(str[0]).append("' and '").append(str[1]).append("' ");;
					sql1.append(" AND f.create_time between '").append(str[0]).append("' and '").append(str[1]).append("' ");;
				}
				sql.append(" ORDER BY f.create_time DESC");
				sql1.append(" ORDER BY f.create_time DESC");
				List<Object[]> objs=this.query(sql.toString(), nextPage*pageSize, pageSize);
				List<FeedBack> vos=new ArrayList<FeedBack>();
				
				for (Object[] obj : objs) {	
					FeedBack vo = new FeedBack();
					vo.setId(Long.valueOf(obj[0].toString()));
					vo.setContent(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
					vo.setUrl(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
					vo.setUserName(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
					vo.setCreateTime(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
					vos.add(vo);
				}
				//执行查询语句
				List<Object[]> obj1=this.query(sql1.toString(), null, null);
				//将得到的查询结果强转成int类型
				int count=Integer.parseInt(obj1.get(0)+"");				
				//调用分页
				Page<FeedBack> page= new MyPage<FeedBack>(nextPage.intValue(),pageSize.intValue(),vos,count);
				//创建结果集对象xr
				XaResult<Page<FeedBack>> xr=new XaResult<Page<FeedBack>>();
				//将page放入xr
				xr.setObject(page);
				return xr;
	}
	
}
